<template>
  <div class="product-detail-page">
    <el-card class="box-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <el-button :icon="ArrowLeft" @click="goBack">返回</el-button>
          <span>商品详情</span>
        </div>
      </template>

      <div class="product-detail-content" v-if="product">
        <div class="product-main">
          <div class="product-image-section">
            <el-image
              :src="getProductImage(product)"
              :alt="product.productName"
              fit="cover"
              class="main-image"
              :preview-src-list="[getProductImage(product)]"
              :initial-index="0"
              loading="lazy"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <span>暂无图片</span>
                </div>
              </template>
            </el-image>
          </div>

          <div class="product-info-section">
            <h1 class="product-title">{{ product.productName }}</h1>
            
            <div class="product-price-section">
              <!-- 会员折扣信息 -->
              <div v-if="product.hasMemberDiscount" class="member-price-section">
                <div class="member-level-badge">
                  <el-tag 
                    :type="getMemberLevelType(product.userMemberLevel)" 
                    size="small"
                    class="member-tag"
                  >
                    {{ product.memberLevelName }}
                  </el-tag>
                  <el-tag type="danger" size="small" class="discount-tag">
                    {{ product.discountDescription }}
                  </el-tag>
                </div>
                
                <div class="price-display">
                  <span class="original-price">¥{{ product.sellingPrice }}</span>
                  <span class="discount-price">¥{{ product.memberDiscountPrice }}</span>
                  <span class="saved-amount">节省 ¥{{ product.savedAmount }}</span>
                </div>
              </div>
              
              <!-- 普通用户价格显示 -->
              <div v-else class="normal-price-section">
                <span class="current-price">¥{{ product.sellingPrice }}</span>
                <div class="member-level-badge">
                  <el-tag type="info" size="small" class="member-tag">
                    {{ product.memberLevelName || '普通用户' }}
                  </el-tag>
                </div>
              </div>
              
              <el-tag 
                :type="product.currentStock > 0 ? 'success' : 'danger'" 
                size="large"
                class="stock-tag"
              >
                库存：{{ product.currentStock }} 件
              </el-tag>
            </div>

            <div class="product-specs">
              <div class="spec-item">
                <span class="spec-label">商品编号：</span>
                <span class="spec-value">{{ product.productCode }}</span>
              </div>
              <div class="spec-item" v-if="product.model">
                <span class="spec-label">型号：</span>
                <span class="spec-value">{{ product.model }}</span>
              </div>
              <div class="spec-item" v-if="product.supplierName">
                <span class="spec-label">供应商：</span>
                <span class="spec-value">{{ product.supplierName }}</span>
              </div>
              <div class="spec-item" v-if="product.categoryName">
                <span class="spec-label">分类：</span>
                <span class="spec-value">{{ product.categoryName }}</span>
              </div>
            </div>

            <div class="purchase-section">
              <div class="quantity-selector">
                <span class="quantity-label">购买数量：</span>
                <el-input-number
                  v-model="purchaseQuantity"
                  :min="1"
                  :max="product.currentStock"
                  controls-position="right"
                  :disabled="product.currentStock <= 0"
                />
              </div>
              
              <div class="total-price">
                <span class="total-label">总价：</span>
                <span class="total-amount">¥{{ finalTotalAmount }}</span>
                <span v-if="product.hasMemberDiscount && purchaseQuantity > 1" class="total-saved">
                  （节省 ¥{{ totalSavedAmount }}）
                </span>
              </div>

              <div class="action-buttons">
                <el-button
                  type="primary"
                  size="large"
                  :disabled="product.currentStock <= 0"
                  @click="handlePurchase"
                  :loading="purchasing"
                >
                  <el-icon><ShoppingCart /></el-icon>
                  立即购买
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 商品详细信息 -->
        <div class="product-details-tabs">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="商品详情" name="details">
              <div class="detail-content">
                <h3>商品信息</h3>
                <table class="detail-table">
                  <tr>
                    <td class="label">商品名称</td>
                    <td>{{ product.productName }}</td>
                  </tr>
                  <tr>
                    <td class="label">商品编号</td>
                    <td>{{ product.productCode }}</td>
                  </tr>
                  <tr v-if="product.model">
                    <td class="label">型号</td>
                    <td>{{ product.model }}</td>
                  </tr>
                  <tr>
                    <td class="label">销售价格</td>
                    <td class="price">¥{{ product.sellingPrice }}</td>
                  </tr>
                  <tr>
                    <td class="label">当前库存</td>
                    <td>{{ product.currentStock }} 件</td>
                  </tr>
                  <tr v-if="product.supplierName">
                    <td class="label">供应商</td>
                    <td>{{ product.supplierName }}</td>
                  </tr>
                  <tr v-if="product.categoryName">
                    <td class="label">商品分类</td>
                    <td>{{ product.categoryName }}</td>
                  </tr>
                </table>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-else-if="!loading" description="商品不存在或已下架" />
    </el-card>

    <!-- 购买确认对话框 -->
    <el-dialog
      v-model="purchaseDialogVisible"
      title="确认购买"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="purchase-confirm">
        <div class="confirm-item">
          <span class="label">商品名称：</span>
          <span>{{ product?.productName }}</span>
        </div>
        <div class="confirm-item">
          <span class="label">单价：</span>
          <span class="price">¥{{ product?.sellingPrice }}</span>
        </div>
        <div class="confirm-item">
          <span class="label">购买数量：</span>
          <span>{{ purchaseQuantity }} 件</span>
        </div>
        <div class="confirm-item total">
          <span class="label">总金额：</span>
          <span class="total-price">¥{{ totalAmount }}</span>
        </div>
        <div class="confirm-item">
          <span class="label">备注：</span>
          <el-input
            v-model="remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
          />
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="purchaseDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPurchase" :loading="purchasing">
            确认购买
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Picture, ShoppingCart } from '@element-plus/icons-vue'
import { getPublicProductDetail } from '@/api/storeProduct'
import { purchaseProduct } from '@/api/purchase'
import defaultProductImage from '@/assets/default-product.svg'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const purchasing = ref(false)
const product = ref(null)
const purchaseQuantity = ref(1)
const remark = ref('')
const activeTab = ref('details')
const purchaseDialogVisible = ref(false)

// 计算总金额（使用会员折扣价）
const finalTotalAmount = computed(() => {
  if (!product.value || !purchaseQuantity.value) {
    return '0.00'
  }
  
  const unitPrice = product.value.hasMemberDiscount 
    ? product.value.memberDiscountPrice 
    : product.value.sellingPrice
    
  return (unitPrice * purchaseQuantity.value).toFixed(2)
})

// 计算总节省金额
const totalSavedAmount = computed(() => {
  if (!product.value?.hasMemberDiscount || !purchaseQuantity.value) {
    return '0.00'
  }
  
  return (product.value.savedAmount * purchaseQuantity.value).toFixed(2)
})

// 原始总金额计算（用于购买确认对话框）
const totalAmount = computed(() => {
  if (product.value?.sellingPrice && purchaseQuantity.value) {
    return (product.value.sellingPrice * purchaseQuantity.value).toFixed(2)
  }
  return '0.00'
})

// 获取会员等级标签类型
const getMemberLevelType = (level) => {
  switch (level) {
    case 'VIP1':
      return 'danger'
    case 'VIP2':
      return 'success'
    case 'VIP3':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取商品图片URL
const getProductImage = (productData) => {
  const imageUrl = productData?.image || defaultProductImage
  console.log(`商品详情页 ${productData?.productName} 的图片URL:`, imageUrl)
  return imageUrl
}

// 获取商品详情
const getProductDetail = async () => {
  const productId = route.params.id
  if (!productId) {
    ElMessage.error('商品ID不能为空')
    goBack()
    return
  }

  try {
    loading.value = true
    const response = await getPublicProductDetail(productId)
    
    if (response.code === 200) {
      product.value = response.data
      // 重置购买数量
      purchaseQuantity.value = 1
    } else {
      ElMessage.error(response.message || '获取商品详情失败')
      goBack()
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
    goBack()
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 处理购买
const handlePurchase = () => {
  if (!product.value) return
  
  if (product.value.currentStock <= 0) {
    ElMessage.error('商品库存不足')
    return
  }
  
  if (purchaseQuantity.value > product.value.currentStock) {
    ElMessage.error(`购买数量不能超过库存数量（${product.value.currentStock}）`)
    return
  }
  
  purchaseDialogVisible.value = true
}

// 确认购买
const confirmPurchase = async () => {
  try {
    purchasing.value = true
    
    const purchaseData = {
      productId: product.value.id,
      purchaseQuantity: purchaseQuantity.value,
      remark: remark.value
    }
    
    const response = await purchaseProduct(purchaseData)
    
    if (response.code === 200) {
      ElMessage.success('购买成功')
      purchaseDialogVisible.value = false
      // 刷新商品信息
      await getProductDetail()
    } else {
      ElMessage.error(response.message || '购买失败')
    }
  } catch (error) {
    console.error('购买失败:', error)
    ElMessage.error('购买失败')
  } finally {
    purchasing.value = false
  }
}

// 页面加载时获取商品详情
onMounted(() => {
  getProductDetail()
})
</script>

<style scoped>
.product-detail-page {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.product-detail-content {
  max-width: 1200px;
  margin: 0 auto;
}

.product-main {
  display: flex;
  gap: 40px;
  margin-bottom: 40px;
}

.product-image-section {
  flex: 0 0 400px;
}

.main-image {
  width: 100%;
  height: 400px;
  border-radius: 8px;
}

.image-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 400px;
  background: #f5f7fa;
  color: #909399;
  border-radius: 8px;
}

.product-info-section {
  flex: 1;
}

.product-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 20px 0;
}

.product-price-section {
  margin-bottom: 30px;
  padding: 20px 0;
  border-bottom: 1px solid #e4e7ed;
}

/* 会员折扣价格样式 */
.member-price-section {
  flex: 1;
}

.member-level-badge {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 15px;
}

.member-tag {
  font-weight: 600;
}

.discount-tag {
  font-weight: 600;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.price-display {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.original-price {
  font-size: 18px;
  color: #909399;
  text-decoration: line-through;
}

.discount-price {
  font-size: 32px;
  font-weight: 600;
  color: #f56c6c;
}

.saved-amount {
  font-size: 16px;
  color: #67c23a;
  font-weight: 600;
  background: #f0f9ff;
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #67c23a;
}

/* 普通用户价格样式 */
.normal-price-section {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 15px;
}

.current-price {
  font-size: 32px;
  font-weight: 600;
  color: #e6a23c;
}

.stock-tag {
  font-size: 14px;
  margin-left: auto;
}

/* 总价部分样式 */
.total-price {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.total-label {
  flex: 0 0 100px;
  font-weight: 600;
  color: #606266;
}

.total-amount {
  font-size: 24px;
  font-weight: 600;
  color: #e6a23c;
}

.total-saved {
  margin-left: 10px;
  font-size: 14px;
  color: #67c23a;
  font-weight: 600;
}

.product-specs {
  margin-bottom: 30px;
}

.spec-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.spec-label {
  flex: 0 0 100px;
  font-weight: 600;
  color: #606266;
}

.spec-value {
  color: #303133;
}

.purchase-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
}

.quantity-selector {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.quantity-label {
  flex: 0 0 100px;
  font-weight: 600;
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

.action-buttons .el-button {
  flex: 1;
  height: 50px;
  font-size: 16px;
}

.product-details-tabs {
  margin-top: 40px;
}

.detail-content h3 {
  margin: 0 0 20px 0;
  color: #303133;
}

.detail-table {
  width: 100%;
  border-collapse: collapse;
}

.detail-table td {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-table .label {
  width: 120px;
  font-weight: 600;
  color: #606266;
}

.detail-table .price {
  font-size: 18px;
  font-weight: 600;
  color: #e6a23c;
}

.purchase-confirm .confirm-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
}

.purchase-confirm .confirm-item.total {
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
  font-weight: 600;
}

.purchase-confirm .label {
  flex: 0 0 100px;
  color: #606266;
}

.purchase-confirm .total-price {
  font-size: 18px;
  color: #e6a23c;
}

@media (max-width: 768px) {
  .product-main {
    flex-direction: column;
    gap: 20px;
  }
  
  .product-image-section {
    flex: none;
  }
  
  .main-image {
    height: 300px;
  }
  
  .product-title {
    font-size: 20px;
  }
  
  .current-price {
    font-size: 24px;
  }
}
</style> 